#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
#include <queue>
#include <deque>
#include <set>
#include <map> 
#include <unordered_set>

#define flr(x, l, r) for (int x = l; x <= r; ++x)
#define frl(x, r, l) for (int x = r; x >= l; --x)
#define fmp(x, t) for (int x = h[t]; ~x; x = ne[x])
#define LL long long
#define mt memset
#define my memcpy
#define szf sizeof
#define INF 0x3f3f3f3f
#define in(x) scanf("%d", &x)
#define out(x) printf("%d", x)
#define inll(x) scanf("%lld", &x)
#define outll(x) printf("%lld", x)
#define pn printf("\n")
#define con continue
#define bk break
#define vc vector
#define pb push_back
#define sz size
#define PII pair<int, int>
#define x first
#define y second
#define P_q priority_queue
#define ft front
#define pf push_front
#define popf pop_front
#define it insert
#define ct count

using namespace std;

const int N = 100010, M = 600010;

int n, m;
int h[N], hs[N], e[M], ne[M], w[M], idx;
int dfn[N], low[N], timestamp;
int scc_cnt, id[N], Size[N];
int stk[N], top;
bool in_stk[N];
int dist[N];

void add(int h[], int a, int b, int c) {
    e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++ ;
}

void tarjan(int u)
{
    dfn[u] = low[u] = ++ timestamp;
    stk[ ++ top] = u, in_stk[u] = true;

    for (int i = h[u]; ~i; i = ne[i])
    {
        int j = e[i];
        if (!dfn[j])
        {
            tarjan(j);
            low[u] = min(low[u], low[j]);
        }
        else if (in_stk[j]) low[u] = min(low[u], dfn[j]);
    }

    if (dfn[u] == low[u])
    {
        ++ scc_cnt;
        int y;
        do {
            y = stk[top -- ];
            in_stk[y] = false;
            id[y] = scc_cnt;
            Size[scc_cnt] ++ ;
        } while (y != u);
    }
}

int main() {
	in(n), in(m);
	
	mt(h, -1, szf h), mt(hs, -1, szf hs);
	flr (i, 1, n) add(h, 0, i, 1);
	while (m -- ) {
	    int t, a, b;
	    in(t), in(a), in(b);
	    if (t == 1) add(h, a, b, 0), add(h, b, a, 0);
	    else if (t == 2) add(h, a, b, 1);
	    else if (t == 3) add(h, b, a, 0);
	    else if (t == 4) add(h, b, a, 1);
	    else add(h, a, b, 0);
	}
	
	tarjan(0);
	
	bool success = true;        
    flr (i, 0, n) {
        fmp (j, i) {
            int k = e[j];
            int a = id[i], b = id[k];
            if (a == b) {
                if (w[j]) {
                    success = false;
                    bk;
                }
            }
            else add(hs, a, b, w[j]);
        }
        if (!success) bk;
    }
	
	if (!success) puts("-1");
	else {
	    frl (i, scc_cnt, 1)
	       for (int j = hs[i]; ~j; j = ne[j]) {
	           int k = e[j];
	           if (dist[k] < dist[i] + w[j])
	                dist[k] = dist[i] + w[j];
	       }
	   
	   LL res = 0;
	   flr (i, 1, scc_cnt) res += (LL)dist[i] * Size[i];
	   
	   outll(res), pn;
	}
	
    return 0;
}